package com.xhy.documents_collection.service.task.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xhy.documents_collection.enums.EmailEnum;
import com.xhy.documents_collection.holder.UserHolder;
import com.xhy.documents_collection.enums.TimingEnum;
import com.xhy.documents_collection.entity.PO.email.EmailSetting;
import com.xhy.documents_collection.entity.PO.task.Task;
import com.xhy.documents_collection.entity.PO.task.TaskTimingRecord;
import com.xhy.documents_collection.mapper.task.TaskTimingRecordMapper;
import com.xhy.documents_collection.scheduler.SchedulerHandler;
import com.xhy.documents_collection.service.EmailSettingService;
import com.xhy.documents_collection.service.async.AsyncService;
import com.xhy.documents_collection.service.task.TaskService;
import com.xhy.documents_collection.service.task.TaskTimingRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xhy.documents_collection.utils.R;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Collection;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xhy
 * @since 2023-03-03
 */
@Service
public class TaskTimingRecordServiceImpl extends ServiceImpl<TaskTimingRecordMapper, TaskTimingRecord> implements TaskTimingRecordService {

    @Resource
    EmailSettingService emailSettingService;
    @Resource
    TaskService taskService;


    @Resource
    SchedulerHandler schedulerHandler;

    @Resource
    @Lazy
    AsyncService asyncService;

    final static String content = "共计{headCount}人,实交{practical}人。没有交作业的人:{noSubmitNames}";

    @Override
    public R addTask(TaskTimingRecord taskTimingRecord) {
        Integer userId = UserHolder.get();
        // 需要配置邮箱
        int count = emailSettingService.count(new LambdaQueryWrapper<EmailSetting>().eq(EmailSetting::getUserId, userId).eq(EmailSetting::getState,true));
        if (count == 0){
            return R.error().message("定时任务需要依赖邮箱,请先配置邮箱");
        }

        // 校验时间 当前时间大于sendTime
        if (new Date().toInstant().isAfter(taskTimingRecord.getSendTime().toInstant())) {
            return R.error().message("选择的日期不可小于当前日期");
        }
        // 校验way
        if (taskTimingRecord.getWay() != EmailEnum.NOTICE.type && taskTimingRecord.getWay() != EmailEnum.SUBMIT.type){
            return R.error().message("请选择合法的方式");
        }
        if (ObjectUtils.isEmpty(taskTimingRecord.getContent())){
            taskTimingRecord.setContent(content);
        }
        // 校验任务是否属于自己
        Task task = taskService.getOne(new LambdaQueryWrapper<Task>().eq(Task::getId,taskTimingRecord.getTaskId()).eq(Task::getUId,userId));

        taskTimingRecord.setTaskName(task.getName());
        taskTimingRecord.setState(TimingEnum.PROCESS.type);
        // 填充发布时间
        taskTimingRecord.setExpire();
        taskTimingRecord.setUserId(userId);
        save(taskTimingRecord);
        // 添加到延迟队列中
        schedulerHandler.add(taskTimingRecord);
        return R.ok().message("添加成功");
    }



    @Override
    public R updateTasks(Collection<TaskTimingRecord> taskTimingRecords) {
        for (TaskTimingRecord taskTimingRecord : taskTimingRecords) {
            Integer userId = UserHolder.get();
            if (ObjectUtils.isEmpty(taskTimingRecord.getContent())){
                taskTimingRecord.setContent(content);
            }
            // 校验任务是否属于自己
            Task task = taskService.getOne(new LambdaQueryWrapper<Task>().eq(Task::getId,taskTimingRecord.getTaskId()).eq(Task::getUId,userId));
            if (ObjectUtils.isEmpty(task)){
                return R.error().message("请选择自己管理的任务进行添加");
            }


            taskTimingRecord.setExpire();
            updateById(taskTimingRecord);
            schedulerHandler.update(taskTimingRecord);
        }
        return R.ok().message("修改成功");

    }

    @Override
    public R removeTaskByIds(List<Integer> ids) {
        Integer userId = UserHolder.get();
        boolean res = remove(new LambdaQueryWrapper<TaskTimingRecord>().in(!ObjectUtils.isEmpty(ids), TaskTimingRecord::getId, ids)
                .eq(TaskTimingRecord::getUserId, userId));
        if (res){
            schedulerHandler.delete(ids);
        }
        return R.ok().message("删除成功");
    }

    @Override
    public void artificialSend(Integer id) {
        TaskTimingRecord taskTimingRecord = getById(id);
        asyncService.addSchedulerTask(taskTimingRecord);
    }

}
